package utils;

//毫无作用的东西,过滤器，阻止未登录的用户使用增删改查功能
import java.io.IOException;
import java.util.List;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@WebFilter("/ZZZHomework/*")  // "/*" 才能生效
public class LoginFilter implements Filter {
	
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {
        
    	HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 获取会话对象
        HttpSession session = httpRequest.getSession(false);  // 使用 false 来避免新建会话
        System.out.print("会话值："+ (session != null ? session.getId() : "无会话"));
        // 获取请求的 URI
        String requestURI = httpRequest.getRequestURI();
        System.out.println("请求的登录界面1: " + requestURI);

        // 不需要检查登录状态的路径，例如登录页面、注册页面等
        if (requestURI.endsWith("/view/Login.jsp") || requestURI.endsWith("/LoginServlet")) {
            chain.doFilter(request, response);  // 允许跳过过滤器
        }

        System.out.println("请求的登录界面2: " + requestURI);

        // 判断请求页面是否是学生相关页面
        if (requestURI.contains("/view/LoginFdy.jsp") || requestURI.contains("/View_SuShe/SuSheFDY_List.jsp")) {
            // 检查会话中是否有 student 属性
        	// 获取会话中属性 "sg"
            List<String> id = session != null ? (List<String>) session.getAttribute("fdy") : null;
            
            // 检查是否存在 "sg" 属性
            if (id == null) {
                // 如果没有 "sg" 属性，则重定向到登录页面
                httpResponse.sendRedirect(httpRequest.getContextPath() + "/view/Login.jsp");
                return;
            }else {
            	chain.doFilter(request, response);  // 允许跳过过滤器
            }

            System.out.print("fdy会话值："+ id);  // 打印获取到的 "sg" 属性值
        }
    }

    public void init(FilterConfig filterConfig) throws ServletException {}
    public void destroy() {}
}
